package com.chehongwei.ioc;

import com.chehongwei.aspect.Aspect;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class MyApplicationContext
    implements ApplicationContext {

    private Aspect aspect;

    private Map<String, Class<?>> beanMap = new HashMap<>();

    @Override
    public Object getBean(
        String beanName)
        throws Exception {
        Object bean;
        bean = createInstance(beanName);
        if (aspect.getPointcut().getClassPattern()
            .equals(bean.getClass().getName())) {
            bean = proxyEnhance(bean);
        }

        return bean;
    }

    private Object proxyEnhance(
        Object bean) {

        return Proxy.newProxyInstance(bean.getClass().getClassLoader(),
            bean.getClass().getInterfaces(),
            new MyInvocationHandler(bean, aspect));
    }

    private Object createInstance(
        String beanName)
        throws Exception {
        return this.beanMap.get(beanName).newInstance();
    }

    @Override
    public void registerBean(
        String beanName,
        Class<?> beanClass) {

        beanMap.put(beanName, beanClass);

    }

    public void setAspect(
        Aspect aspect) {
        this.aspect = aspect;
    }
}
